package com.lzy.shops.service.impl;

import com.lzy.shops.bean.GoodsCart;
import com.lzy.shops.bean.PageBean;
import com.lzy.shops.bean.Search;
import com.lzy.shops.mapper.GoodsCartMapper;
import com.lzy.shops.service.GoodsCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsCarServiceImpl implements GoodsCarService {

    @Autowired
    private GoodsCartMapper mapper;

    @Override
    public PageBean findAll(Integer userId, Search search) {
        PageBean pageBean = new PageBean();
        try {
            List<GoodsCart> all = mapper.findAll(userId,search);
            Integer allCount = mapper.findAllCount(userId);
            if(allCount>0){
                pageBean.setTotalRecords(allCount);
                pageBean.setList(all);
            }else{
                pageBean.setList(new ArrayList());
            }
        } catch (Exception e) {
            pageBean = new PageBean();
        }
        return pageBean;
    }

    @Override
    public Integer addGoodsCar(Integer shopId, Integer nums, Integer userId) {
        return mapper.addGoodsCar(shopId,nums,userId);
    }

    @Override
    public Integer findByGoodsCarNums(Integer shopId, Integer userId) {
        return mapper.findByGoodsCarNums(shopId,userId);
    }

    @Override
    public Boolean updateGoodsCarNums(Integer carId, Integer userId,Integer nums) {
        try{
            GoodsCart goods = mapper.findByGoodsCar(carId, userId);
            if(goods!=null){
                Integer integer = mapper.updateGoodsCarNums(goods.getCarId().intValue(), nums);
                if(integer==1){
                    return true;
                }
            }else throw new RuntimeException("数据异常");
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        return false;
    }

    @Override
    public Integer deleteGoodsCar(Integer userId, Integer carId) {
        return mapper.deleteGoodsCar(userId,carId);
    }

    @Override
    public Integer deleteGoodsCars(String uId, String carId) {
        Integer userId = Integer.valueOf(uId);
        String[] ids = carId.split(",");
        Integer count = 0;
        for (String id : ids) {
            Integer integer = mapper.deleteGoodsCar(userId, Integer.valueOf(id));
            if(integer==1){
                count++;
            }
        }
        return count;
    }
}
